'use client';

import React from 'react';
import { AutoSaveStatus } from '@/hooks/use-auto-save';
import { Check, Save, AlertTriangle, Clock, CloudOff, RefreshCw } from 'lucide-react';

interface AutoSaveIndicatorProps {
  status: AutoSaveStatus;
  lastSavedAt: Date | null;
  className?: string;
  retry?: () => void;
  saveAttempts?: number;
}

export function AutoSaveIndicator({ 
  status, 
  lastSavedAt, 
  className = '',
  retry,
  saveAttempts = 0
}: AutoSaveIndicatorProps) {
  // 格式化上次保存时间
  const formattedTime = lastSavedAt 
    ? new Date(lastSavedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    : '';
    
  // 根据状态显示不同的图标和文字
  const renderStatus = () => {
    switch (status) {
      case 'saving':
        return (
          <div className="flex items-center text-muted-foreground animate-pulse">
            <RefreshCw className="h-3 w-3 mr-2 animate-spin" />
            <span>自动保存中...</span>
          </div>
        );
      
      case 'saved':
        return (
          <div className="flex items-center text-green-600">
            <Check className="h-3 w-3 mr-2" />
            <span>已自动保存 {formattedTime}</span>
          </div>
        );
        
      case 'manually_saved':
        return (
          <div className="flex items-center text-blue-600">
            <Save className="h-3 w-3 mr-2" />
            <span>已手动保存 {formattedTime}</span>
          </div>
        );
      
      case 'error':
        return (
          <div className="flex items-center text-amber-600">
            <AlertTriangle className="h-3 w-3 mr-2" />
            <span>保存失败</span>
            {retry && saveAttempts < 3 && (
              <button 
                onClick={retry}
                className="ml-2 text-xs underline hover:text-amber-800 focus:outline-none"
              >
                重试
              </button>
            )}
          </div>
        );
        
      case 'conflict':
        return (
          <div className="flex items-center text-red-600">
            <AlertTriangle className="h-3 w-3 mr-2" />
            <span>版本冲突</span>
          </div>
        );
        
      case 'pending':
        return (
          <div className="flex items-center text-blue-400">
            <Clock className="h-3 w-3 mr-2" />
            <span>待保存</span>
          </div>
        );
      
      case 'idle':
      default:
        if (lastSavedAt) {
          return (
            <div className="flex items-center text-muted-foreground">
              <Clock className="h-3 w-3 mr-2" />
              <span>上次保存 {formattedTime}</span>
            </div>
          );
        }
        return null;
    }
  };
  
  return (
    <div className={`auto-save-indicator text-xs ${className}`}>
      {renderStatus()}
    </div>
  );
} 